package com.yuzhitong.shapi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.android.material.appbar.AppBarLayout;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.base.BaseMvpActivity;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.base.recycler.BaseAdapter;
import com.yuzhitong.shapi.base.recycler.BaseViewHolder;
import com.yuzhitong.shapi.bean.CategoryBean;
import com.yuzhitong.shapi.bean.MovieBean;
import com.yuzhitong.shapi.contract.CategoryContract;
import com.yuzhitong.shapi.presenter.CategoryPresenter;
import com.yuzhitong.shapi.util.GlideUtil;
import com.yuzhitong.shapi.util.StringUtil;
import com.yuzhitong.shapi.util.UiUtil;
import com.yuzhitong.shapi.widget.ScoreView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Brsya
 * CreateData: 2022/5/8  20:10
 * Description:
 * 分类筛选页
 */
public class CategoryActivity extends BaseMvpActivity<CategoryPresenter> implements CategoryContract.View {

    private RelativeLayout llPageTitleBox;
    private TextView tvPageTitle;
    private AppBarLayout ablCategoryBox;
    private TextView tvCategoryText;
    private LinearLayout llTitleBackBox;
    private SwipeRefreshLayout srlRefresh;
    private RecyclerView rvMovieList;
    private CommonTabLayout stlCheckedType;
    private CommonTabLayout stlCheckedTags;
    private CommonTabLayout stlCheckedArea;
    private CommonTabLayout stlCheckedYear;
    private CommonTabLayout stlCheckedSort;

    private TextView bottomTextView;


    private BaseAdapter<MovieBean> adapter;


    private ArrayList<CustomTabEntity> typeDataList;
    private ArrayList<CustomTabEntity> tagsDataList;
    private ArrayList<CustomTabEntity> areaDataList;
    private ArrayList<CustomTabEntity> yearDataList;
    private ArrayList<CustomTabEntity> sortDataList;


    private String movieType;
    private String movieTypeName;
    private String movieTags;
    private String movieTagsName;
    private String movieArea;
    private String movieAreaName;
    private String movieYear;
    private String movieYearName;
    private String movieSort;
    private String movieSortName;

    private int pageNumber = 0;
    private List<CategoryBean> categoryBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        setDarkStatus();

        initView();
        initData();
    }


    private void initView() {
        llPageTitleBox = findViewById(R.id.ll_page_title_box);
        tvPageTitle = findViewById(R.id.tv_page_title);
        llTitleBackBox = findViewById(R.id.ll_title_back_box);
        rvMovieList = findViewById(R.id.rv_movie_list);
        ablCategoryBox = findViewById(R.id.abl_category_box);
        tvCategoryText = findViewById(R.id.tv_category_text);
        stlCheckedType = findViewById(R.id.stl_checked_type);
        stlCheckedTags = findViewById(R.id.stl_checked_tags);
        stlCheckedArea = findViewById(R.id.stl_checked_area);
        stlCheckedYear = findViewById(R.id.stl_checked_year);
        stlCheckedSort = findViewById(R.id.stl_checked_sort);
        srlRefresh = findViewById(R.id.srl_refresh);
    }

    private void initData() {

        UiUtil.setStatusPadding(this, llPageTitleBox);
        rvMovieList.setLayoutManager(new GridLayoutManager(this, 3));
        rvMovieList.setAdapter(adapter = new BaseAdapter<MovieBean>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(CategoryActivity.this).inflate(R.layout.item_movie, parent, false);
                return new BaseViewHolder(itemView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieBean data) {
                ImageView ivMovieImg = viewHolder.findViewById(R.id.iv_movie_img);
                TextView tvMovieTitle = viewHolder.findViewById(R.id.tv_movie_title);
                ScoreView scoreView = viewHolder.findViewById(R.id.sv_score_box);

                tvMovieTitle.setText(data.getName());
                GlideUtil.loadRound(ivMovieImg, data.getCoverUrl(), 4);
                scoreView.setScore(data.getDoubanScore());
            }
        });

        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<MovieBean>() {
            @Override
            public void onItemClick(int position, MovieBean data) {
                Intent intent = new Intent(CategoryActivity.this, PlayNewActivity.class);
                intent.putExtra(Contents.INTENT_MOVIE_DETAIL, data);
                startActivity(intent);
            }
        });

        rvMovieList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (UiUtil.isSlideToBottom(recyclerView)) {
                    getMovieList(false);
                }
            }
        });
        View bottomView = LayoutInflater.from(this).inflate(R.layout.item_no_more_data, null, false);
        bottomTextView = bottomView.findViewById(R.id.tv_no_more_data_text);
        adapter.setBottomView(bottomView);


        srlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getMovieList();
            }
        });

        if (getIntent() != null) {
            if (getIntent().getStringExtra(Contents.INTENT_MOVIE_TYPE) != null) {
                movieType = getIntent().getStringExtra(Contents.INTENT_MOVIE_TYPE);
            }
            if (getIntent().getStringExtra(Contents.INTENT_MOVIE_SORT) != null) {
                movieSort = getIntent().getStringExtra(Contents.INTENT_MOVIE_SORT);
            }
        }

        ablCategoryBox.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int totalScrollRange = appBarLayout.getTotalScrollRange();
                if (0 == totalScrollRange + verticalOffset) {
                    tvCategoryText.setVisibility(View.VISIBLE);
                } else {
                    tvCategoryText.setVisibility(View.GONE);
                }
            }
        });

        typeDataList = new ArrayList<>();
        tagsDataList = new ArrayList<>();
        areaDataList = new ArrayList<>();
        yearDataList = new ArrayList<>();
        sortDataList = new ArrayList<>();

        stlCheckedType.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = typeDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieType = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieTypeName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                tagsDataList.clear();

                for (CategoryBean categoryBean : categoryBeans) {
                    if ("type".equals(categoryBean.getCode())) {
                        int selectIndex = 0;
                        CategoryBean.ChailDTO chailDTO1 = new CategoryBean.ChailDTO();
                        chailDTO1.setCategoryName("全部");
                        chailDTO1.setCode("");
                        tagsDataList.add(chailDTO1);
                        if (position == 0) {
                            for (int i = 0; i < categoryBean.getChail().size(); i++) {
                                tagsDataList.addAll(categoryBean.getChail().get(i).getChail());
                            }
                        } else {
                            tagsDataList.addAll(categoryBean.getChail().get(position - 1).getChail());
                        }
                    }
                }
                movieTags = "";
                stlCheckedTags.setCurrentTab(0);
                stlCheckedTags.setTabData(tagsDataList);
                stlCheckedTags.notifyDataSetChanged();
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedTags.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = tagsDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieTags = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieTagsName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedArea.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = areaDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieArea = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieAreaName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedYear.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = yearDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieYear = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieYearName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedSort.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = sortDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieSort = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieSortName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        llTitleBackBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        presenter.getCategory();

    }

    @Override
    public void showLoading() {
        super.showLoading();
        srlRefresh.setRefreshing(true);
        bottomTextView.setText(getString(R.string.list_load_more_data));
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        srlRefresh.setRefreshing(false);
    }


    private void getMovieList(){
        getMovieList(true);
    }

    private void getMovieList(boolean isFirst) {
        StringBuffer title = new StringBuffer();
        if (StringUtil.isEmpty(movieTypeName)) {
            title.append("全部");
        }else{
            title.append(movieTypeName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieTagsName)) {
            title.append("全部");
        }else{
            title.append(movieTagsName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieAreaName)) {
            title.append("全部");
        }else{
            title.append(movieAreaName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieYearName)) {
            title.append("全部");
        }else{
            title.append(movieYearName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieSortName)) {
            title.append("全部");
        }else{
            title.append(movieSortName);
        }
        title.append(" - ");
        if (title.length() > 2) {
            title.delete(title.length() - 3, title.length());
            tvCategoryText.setText(title);
        } else {
            tvCategoryText.setText("-");
        }
        if (isFirst) {
            pageNumber = 1;
        }else{
            pageNumber++;
        }
        presenter.getMovieList(pageNumber, movieType, movieTags, movieArea, movieYear, movieSort);
    }


    @Override
    protected void initPresenter() {
        presenter = new CategoryPresenter();
        presenter.attachView(this);
    }

    @Override
    public void showCategory(List<CategoryBean> categoryBeans) {
        this.categoryBeans = categoryBeans;
        for (CategoryBean categoryBean : categoryBeans) {
            switch (categoryBean.getCode()) {
                case "type":
                    movieType = initCheckedData(stlCheckedType, typeDataList, categoryBean.getChail(), movieType);
                    List<CategoryBean.ChailDTO> allTags = new ArrayList<>();
                    for (CategoryBean.ChailDTO chailDTO : categoryBean.getChail()) {
                        allTags.addAll(chailDTO.getChail());
                    }
                    movieTags = initCheckedData(stlCheckedTags, tagsDataList, allTags, movieTags);
                    break;
                case "tags":
//                    movieTags = initCheckedData(stlCheckedTags, tagsDataList, categoryBean.getChail(), movieTags);
                    break;
                case "area":
                    movieArea = initCheckedData(stlCheckedArea, areaDataList, categoryBean.getChail(), movieArea);
                    break;
                case "year":
                    movieYear = initCheckedData(stlCheckedYear, yearDataList, categoryBean.getChail(), movieYear);
                    break;
                case "sort":
                    movieSort = initCheckedData(stlCheckedSort, sortDataList, categoryBean.getChail(), movieSort);
                    break;
            }
        }
        ablCategoryBox.setVisibility(View.VISIBLE);

        getMovieList();
    }


    private String initCheckedData(CommonTabLayout view, ArrayList<CustomTabEntity> dataList
            , List<CategoryBean.ChailDTO> dataRequest, String selectStr) {
        int selectIndex = 0;
        CategoryBean.ChailDTO chailDTO1 = new CategoryBean.ChailDTO();
        chailDTO1.setCategoryName("全部");
        chailDTO1.setCode("");
        dataList.add(chailDTO1);
        if (selectStr != null) {
            for (int i = 0; i < dataRequest.size(); i++) {
                CategoryBean.ChailDTO chailDTO = dataRequest.get(i);
                if (selectStr.equals(chailDTO.getCode())) {
                    selectIndex = i + 1;
                }
                dataList.add(chailDTO);
            }
        } else {
            dataList.addAll(dataRequest);
        }
        if (dataList.size() > 0) {
            view.setTabData(dataList);
            view.setCurrentTab(selectIndex);
            if (dataList.get(selectIndex) instanceof CategoryBean.ChailDTO) {
                return ((CategoryBean.ChailDTO) dataList.get(selectIndex)).getCode();
            }
        }
        view.setVisibility(View.GONE);
        return selectStr;
    }

    @Override
    public void showMovieList(List<MovieBean> movieBeans) {
        if (pageNumber == 1) {
            adapter.setDataList(movieBeans);
        }else{
            adapter.addData(movieBeans);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showNoMore() {
        bottomTextView.setText(getString(R.string.list_no_more_data));
    }
}
